<?php

/**
 * nomination actions.
 *
 * @package    lomejorde
 * @subpackage nomination
 * @author     Your name here
 * @version    SVN: $Id: actions.class.php 23810 2009-11-12 11:07:44Z Kris.Wallsmith $
 */

class nominationActions extends sfActions {
    
    public function executeGetCandidates(sfWebRequest $request)
    {
        $category = $this->getRoute()->getObject();
        
        $this->getResponse()->setContentType('application/json');

        $string = $request->getParameter('term');

        $limit = $request->getParameter('limit',5);

        $results = Doctrine::getTable('Candidate')->getCandidatesByCategoryIdAndNameLike($category->getId(), $string, $limit);
        
        $candidates = array();

        foreach ($results as $key => $candidate) {
            $c = array();
            
            $c['label'] = $candidate->getName();
            
            $c['desc'] = $candidate->getTwitter() ?  '@'.$candidate->getTwitter() : $candidate->getDescription() ? $candidate->getDescription() : '';
            
            $c['icon'] = $candidate->getThumb();
            
            $c['value'] = $candidate->getId();
            
            $candidates[$key] = $c;
        }

        return $this->renderText(json_encode($candidates));
    }

    public function executeIndex(sfWebRequest $request) {
        $this->categories = $this->getRoute()->getObjects();
        
        $this->categories_done = $this->getUser()->getGuardUser()->getCategoriesDoneNomination();
        
        if($request->isMethod('post') || strcmp($request->getParameter('type'),'success') == 0) {
            $this->setLayout(false);
        }
    }

    public function executeShow(sfWebRequest $request) {
        $this->nomination = $this->getRoute()->getObject();
    }

    public function executeNew(sfWebRequest $request) {
        
        $category = $this->getRoute()->getObject();
        
        $user = $this->getUser()->getGuardUser();

        $nomination = new Nomination();

        $nomination->setCategory($category);
        
        $nomination->setUser($user);

        $this->form = new NominationForm($nomination, array(
                    'category_id' => $category->getId()
                ));
    }

    public function executeCreate(sfWebRequest $request) {
        $category = $this->getRoute()->getObject();
        
        $user = $this->getUser()->getGuardUser();
        
        $nomination = new Nomination();
        
        $nomination->setCategory($category);
        
        $nomination->setUser($user);

        $this->form = new NominationForm($nomination);

        $this->processForm($request, $this->form);

        $this->setTemplate('new');
        
        $this->setLayout(false);
    }

    public function executeEdit(sfWebRequest $request) {
        $category = $this->getRoute()->getObject();
        
        $nomination = Doctrine::getTable('Nomination')->getNominationByCategoryIdAndUserId($category->getId(), $this->getUser()->getGuardUser()->getId());
        
        $this->form = new NominationForm($nomination);
        
        $this->form->setDefault('candidate_id', '');
        
        $this->setLayout(false);
    }

    public function executeUpdate(sfWebRequest $request) {
        $this->form = new NominationForm($this->getRoute()->getObject());
        
        $this->form->setDefault('candidate_id', '');
        
        $this->processForm($request, $this->form);
        
        $this->setTemplate('edit');
        
        $this->setLayout(false);
    }
    
    protected function processForm(sfWebRequest $request, sfForm $form) {
        if($form->bind($request->getParameter($form->getName()), $request->getFiles($form->getName()))){
            if ($form->isValid()) {
                
                $form->save();
                
                $this->redirect($this->getController()->genUrl(array('sf_route' => 'nominaciones'), false).'?type=success');
            }
        } else {
            self::saveNomination($request->getParameter($form->getName()));
            
            $this->redirect($this->getController()->genUrl(array('sf_route' => 'nominaciones'), false).'?type=success');
        }
    }
    
    static function saveNomination(array $values){
        $categories = array(
            'El Café'=> 'cafe',
            'Bala Fria'=> 'balafria',
            'StandUpero' => 'standup',
            'Espacio Cultural' => 'espaciocultural',
            'Espacio Deportivo' => 'espaciodeportivo',
            'Festival Cultural' => 'festivalcultural',
            'La Fiesta' => 'fiesta',
            'Local Nocturno' => 'localnocturno',
            'Mercado de Diseño' => 'mercadodiseno',
            'Festival Musical' => 'festivalmusical',
            'Obra de teatro' => 'obrateatro',
            'La Plaza' => 'plaza',
            'Desayuno' => 'desayuno',
            'Teatro' => 'teatro',
            'Trago' => 'trago',
        );
        
        $category = Doctrine::getTable('Category')->findOneBy('id', $values['category_id']);
        
        $candidate = new Candidate();
        
        $candidate->setName($values['autocomplete_input']);
            
        $candidate->setThumb($categories[$category->getName()].'.gif');
        
        $candidate->setActive(false);
        
        $candidate->save();
        
        $category_candidate = new CategoryCandidate();
            
        $category_candidate->setCandidate($candidate);

        $category_candidate->setCategory($category);

        $category_candidate->save();
        
        $nomination = Doctrine::getTable('Nomination')->getNominationByCategoryIdAndUserId($category->getId(), $values['user_id']);
            
        if(!$nomination){
            $nomination = new Nomination();

            $nomination->setUserId($values['user_id']);

            $nomination->setCategory($category);
        }
        
        $nomination->setCandidate($candidate);
        
        $nomination->save();
    }
    
    public function executeThanks(sfWebRequest $request){
        $this->fb_app_id = sfConfig::get('app_facebook_appid');
        
        $this->nomination = $this->getRoute()->getObject();
        
        $this->categories = Doctrine::getTable('Category')->findAll();
        
        $this->categories_done = $this->getUser()->getGuardUser()->getCategoriesDoneNomination();
        
        $this->setLayout(false);
    }
    
    public function executeNewCandidate(sfWebRequest $request) {
        $this->category = $this->getRoute()->getObject();
        
        $this->form = new CandidateForm(new Candidate());
        
        $this->setLayout(false);
    }
    
    public function executeCreateCandidate(sfWebRequest $request) {
        $this->category = $this->getRoute()->getObject();
        
        $this->form = new CandidateForm(new Candidate());

        $this->processCandidateForm($request, $this->form, $this->category, $this->getUser()->getGuardUser());

        $this->setTemplate('newCandidate');
        
        $this->setLayout(false);
    }
    
    protected function processCandidateForm(sfWebRequest $request, sfForm $form, Category $category, sfGuardUser $user) {
        $form->bind($request->getParameter($form->getName()));
        
        if ($form->isValid()) {
            $candidate = $form->save();
            
            $categories = array(
                'El Café'=> 'cafe',
                'Bala Fria'=> 'balafria',
                'StandUpero' => 'standup',
                'Espacio Cultural' => 'espaciocultural',
                'Espacio Deportivo' => 'espaciodeportivo',
                'Festival Cultural' => 'festivalcultural',
                'La Fiesta' => 'fiesta',
                'Local Nocturno' => 'localnocturno',
                'Mercado de Diseño' => 'mercadodiseno',
                'Festival Musical' => 'festivalmusical',
                'Obra de teatro' => 'obrateatro',
                'La Plaza' => 'plaza',
                'Desayuno' => 'desayuno',
                'Teatro' => 'teatro',
                'Trago' => 'trago',
            );
            
            $candidate->setThumb($categories[$category->getName()].'.gif');
            
            $candidate->setActive(false);
            
            $category_candidate = new CategoryCandidate();
            
            $category_candidate->setCandidate($candidate);
            
            $category_candidate->setCategory($category);
            
            $category_candidate->save();
            
            $nomination = Doctrine::getTable('Nomination')->getNominationByCategoryIdAndUserId($category->getId(), $user->getId());
            
            if(!$nomination){
                $nomination = new Nomination();
                
                $nomination->setUser($user);
                
                $nomination->setCategory($category);
            }
            
            $nomination->setCandidate($candidate);
            
            $nomination->save();
            
            $this->redirect($this->getController()->genUrl(array('sf_route' => 'nominaciones'), false).'?type=success');
        }
    }
    
    public function executeViewNominations(sfWebRequest $request){
        $user = $this->getRoute()->getObject();
        
        $this->pending_categories = Doctrine::getTable('Category')->getCategoriesNotIn($user->getCategoriesDoneNomination());
        
        $this->nominations = $this->getUser()->getGuardUser()->getNominations();
        
        $this->short_url = $this->get_bitly_short_url(
                $this->getController()->genUrl(array('sf_route' => 'show_user_nominations', 'sf_subject' => $user), true),
                sfConfig::get('app_bitly_login'),
                sfConfig::get('app_bitly_apikey')
        );
        
        $this->fb_app_id = sfConfig::get('app_facebook_appid');
        
        $this->setLayout(false);
    }
    
    /* returns the shortened url */
    protected function get_bitly_short_url($url, $login, $apikey, $format='txt') {
        $connectURL = 'http://api.bit.ly/v3/shorten?login='.$login.'&apiKey='.$apikey.'&longUrl='.urlencode($url).'&format='.$format;
        return $this->curl_get_result($connectURL);
    }

    /* returns expanded url */
    protected function get_bitly_long_url($url, $login, $apikey, $format='txt') {
        $connectURL = 'http://api.bit.ly/v3/expand?login='.$login.'&apiKey='.$apikey.'&shortUrl='.urlencode($url).'&format='.$format;
        return $this->curl_get_result($connectURL);
    }

    /* returns a result form url */
    protected function curl_get_result($url) {
        $ch = curl_init();
        $timeout = 5;
        curl_setopt($ch,CURLOPT_URL,$url);
        curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);
        curl_setopt($ch,CURLOPT_CONNECTTIMEOUT,$timeout);
        $data = curl_exec($ch);
        curl_close($ch);
        return $data;
    }
}
